package com.ebupt.migu.music.common.webconfig;

import com.ebupt.migu.common.pojo.Topic;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

@Slf4j
@Aspect
@Component
public class RequestIdAspect {

    @Resource
    private HttpServletRequest request;

    // 定义切点，拦截所有的@RestController注解的请求方法
    @Pointcut("within(@org.springframework.web.bind.annotation.RestController *)")
    public void requestPointcut() {
    }

    // 在切点方法执行前进行拦截处理
    @Before("requestPointcut()")
    public void beforeRequest(JoinPoint joinPoint) {
        // 生成一个默认的唯一RequestId（使用UUID示例）
        String requestId = UUID.randomUUID().toString();
        // 将RequestId放入MDC中，方便Logback日志输出时使用
        MDC.put(Topic.REQUEST_ID_KEY, requestId);
    }

    @After("requestPointcut()")
    public void afterRequest(JoinPoint joinPoint) {
        MDC.remove(Topic.REQUEST_ID_KEY);
    }
}
